//
//  MusicManager.m
//  RGBLight
//
//  Created by 赵鹏宇 on 16/1/18.
//  Copyright © 2016年 赵鹏宇. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

#import "MusicManager.h"
#import "Song.h"

#define AlbumName @"AlbumName"
#define ArtistName @"ArtistName"
#define SongsArray @"SongsArray"

@interface MusicManager ()
@property (nonatomic,strong) NSMutableArray *tempAlbum;
@property (nonatomic,strong) NSMutableArray *tempArtist;

@end

@implementation MusicManager

+ (instancetype)share
{
    static MusicManager *m = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        m = [[MusicManager alloc] init];
    });
    return m;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.songs = [NSMutableArray array];
        self.artists = [NSMutableArray array];
        self.albums = [NSMutableArray array];
        self.likes = [NSMutableArray array];
        self.tempAlbum = [NSMutableArray array];
        self.tempArtist = [NSMutableArray array];
        [self QueryAllMusic];
    }
    return self;
}

- (void)loadMusic
{
    [self.songs removeAllObjects];
    [self QueryAllMusic];
    [self p_requestAppleMusicAccess];
}

- (void)p_requestAppleMusicAccess
{
    MPMediaLibraryAuthorizationStatus authStatus = [MPMediaLibrary authorizationStatus];
    if (authStatus == MPMediaLibraryAuthorizationStatusNotDetermined) {
        // 如果还未请求过权限，先请求权限，如果同意则加载音乐
        [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status) {
            if (status == MPMediaLibraryAuthorizationStatusAuthorized) {
                [self queryPodMusic];
            }
        }];
    } else if (authStatus == MPMediaLibraryAuthorizationStatusAuthorized) {
        // 如果已经同意加载音乐
        [self queryPodMusic];
    }
}

- (void)queryPodMusic
{
    // 方法一：
    //    MPMediaQuery *musicQuery = [MPMediaQuery songsQuery];
    // 方法二：
    // 1.创建媒体选择队列（从ipod库中读出音乐文件）
    MPMediaQuery *musicQuery = [[MPMediaQuery alloc] init];
    // 2.创建读取条件(类似于对数据做一个筛选)  Value：作用等同于MPMediaType枚举值
    MPMediaPropertyPredicate *albumNamePredicate =
    [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:MPMediaTypeMusic] forProperty: MPMediaItemPropertyMediaType];
    //3.给队列添加读取条件
    [musicQuery addFilterPredicate:albumNamePredicate];
    NSArray *mediaItems = [musicQuery items];
    for (MPMediaItem *mediaItem in mediaItems) {
        NSURL *URL = mediaItem.assetURL;
        if (URL) {
            // 歌曲名称
            NSString *name = mediaItem.title;
            // 歌手
            NSString *artist = mediaItem.artist;
            NSTimeInterval duration = mediaItem.playbackDuration;
            NSLog(@"name(%@), artist(%@), musicUrl(%@)", name, artist, URL);
            Song *tempsong = [[Song alloc] init];
            tempsong.songTitle = (name && name.length > 1) ? name : @"";
            tempsong.songURL = URL;
            tempsong.sumTime = duration;
            tempsong.songArtist = (artist && artist.length > 1) ? artist : @"未知歌手";
            [self.songs addObject:tempsong];
        }
    }
}

- (void)QueryArtistMusic
{
    NSArray *temp = [NSArray array];
    NSSet *set = [NSSet setWithArray:self.tempArtist];
    temp = [set allObjects];
    self.tempArtist = nil;
    for (NSString *artist in temp) {
        NSMutableArray *arr = [NSMutableArray array];
        for (Song *item in self.songs)
        {
            if ([item.songArtist isEqualToString:artist]) {
                [arr addObject:item];
            }
        }
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:artist,ArtistName,arr,SongsArray, nil];
        [self.artists addObject:dic];
    }
}

- (void)QueryAlbumMusic
{
    NSArray *temp = [NSArray array];
    NSSet *set = [NSSet setWithArray:self.tempAlbum];
    temp = [set allObjects];
    self.tempAlbum = nil;
    for (NSString *album in temp) {
        NSMutableArray *arr = [NSMutableArray array];
        for (Song *item in self.songs)
        {
            if ([item.songAlbum isEqualToString:album]) {
                [arr addObject:item];
            }
        }
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:album,AlbumName,arr,SongsArray, nil];
        [self.albums addObject:dic];
    }
}

- (void)QueryAllMusic
{
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *songsDirectory = [paths objectAtIndex:0];//沙盒地址
    
    NSLog(@"%@",songsDirectory);
    
    NSBundle *songBundle=[NSBundle bundleWithPath:songsDirectory];
    NSString *bundlePath=[songBundle resourcePath];
    
    NSArray *arrMp3=[NSBundle pathsForResourcesOfType:@"mp3" inDirectory:bundlePath];
    //文件管理 获取文件属性
    NSFileManager *filM = [NSFileManager defaultManager];
    int i = 0;
    for (NSString *filePath in arrMp3) {
        //IOS的资源路径封装，网络文件用urlWithPath:
        Song *song = [[Song alloc] init];
        //取得音频数据
        NSURL *fileURL=[NSURL fileURLWithPath:filePath];
        song.songURL = fileURL;
        
        AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
        song.sumTime = player.duration;
        AVURLAsset *mp3Asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
        
        
        for (NSString *format in [mp3Asset availableMetadataFormats]) {
            for (AVMetadataItem *metadataItem in [mp3Asset metadataForFormat:format]) {
                //artwork这个key对应的value里面存的就是封面缩略图，其它key可以取出其它摘要信息，例如title - 标题
                if ([metadataItem.commonKey isEqualToString:AVMetadataCommonKeyTitle]) {//歌曲名称
                    song.songTitle = metadataItem.stringValue;
                    GWLog(@"SongName：%@",song.songTitle);
                }
                if ([metadataItem.commonKey isEqualToString:AVMetadataCommonKeyArtist]) {//歌手
                    [self.tempArtist addObject:metadataItem.stringValue];
                    song.songArtist = metadataItem.stringValue;
                    GWLog(@"Singer：%@",song.songArtist);
                }
                if ([metadataItem.commonKey isEqualToString:AVMetadataCommonKeyAlbumName]) {//专辑名称
                    [self.tempAlbum addObject:metadataItem.stringValue];
                    song.songAlbum = metadataItem.stringValue;
                    GWLog(@"Album：%@",song.songAlbum);
                }
                if ([metadataItem.commonKey isEqualToString:AVMetadataCommonKeyArtwork]) {//歌曲封面(默认大小640x640)
                    UIImage *coverImage = [UIImage imageWithData:(NSData*)metadataItem.value];
                    song.songImage = coverImage;
                }
            }
        }
        NSDictionary *dict = [filM attributesOfItemAtPath:filePath error:nil];
        song.songSize = [NSString stringWithFormat:@"%.2f",[dict[@"NSFileSize"] floatValue] / (1024 * 1024)];
        if ([song.songTitle isEqualToString:@""]) {
            NSFileManager * fm = [NSFileManager defaultManager];
            
            NSArray  *arr = [fm  contentsOfDirectoryAtPath:songsDirectory error:nil];
            NSArray *array = [arr[i] componentsSeparatedByString:@"."];
            song.songTitle = array[0];
        }
        [self.songs addObject:song];
        i++;
    }
}

- (void)addSongToLikesWithSong:(Song *)song
{
    int flag = 0;
    NSUserDefaults *  u = [NSUserDefaults standardUserDefaults];
    NSArray * aa = [u objectForKey:@"likes"];
    NSMutableArray * a = [NSMutableArray arrayWithArray:aa];
    NSMutableString * s = [NSMutableString stringWithString:song.songTitle];
    [s appendString:song.songArtist];
    [s appendString:song.songAlbum];
    for (int i = 0; i < aa.count; i++) {
        NSString * ur = aa[i];
        if ([ur isEqualToString:[NSString stringWithString:s]])
        {
            flag = 1;
            break;
        }
    }
    if (flag == 0) {
        [a addObject:[NSString stringWithString:s]];
        NSArray * j = [NSArray arrayWithArray:a];
        [[NSUserDefaults standardUserDefaults] setObject:j forKey:@"likes"];
    }
}

- (void)deleteSongFromLikesWithSong:(Song *)song
{
    NSUserDefaults *  u = [NSUserDefaults standardUserDefaults];
    NSArray * aa = [u objectForKey:@"likes"];
    NSMutableArray * a = [NSMutableArray arrayWithArray:aa];
    NSMutableString * s = [NSMutableString stringWithString:song.songTitle];
    [s appendString:song.songArtist];
    [s appendString:song.songAlbum];
    [a removeObject:[NSString stringWithString:s]];
    [u setObject:[NSArray arrayWithArray:a] forKey:@"likes"];
}
- (void)removeFromSuperviewPersentOfAlpha:(double)x
{
    if ([self.delegate respondsToSelector:@selector(contentViewAddToContentViewPersentOfAlpha:)])
    {
        [self.delegate contentViewAddToContentViewPersentOfAlpha:x];
    }
}
- (NSMutableArray *)likes
{
    NSUserDefaults *  u = [NSUserDefaults standardUserDefaults];
    NSArray * a = [u objectForKey:@"likes"];
    NSMutableArray * arr = [NSMutableArray array];
    NSLog(@"%@",self.songs);
    for (int i = 0; i < a.count; i++) {
        NSString * s = a[i];
        for (int j = 0; j < self.songs.count; j++) {
            Song * song = self.songs[j];
            NSMutableString * ss = [NSMutableString stringWithString:song.songTitle];
            [ss appendString:song.songArtist];
            [ss appendString:song.songAlbum];
            if ([s isEqualToString:[NSString stringWithString:ss]]) {
                [arr addObject:song];
            }
        }
    }
    return arr;
}
@end
